<?php
/**
 * Created by : qicaitong.net
 * User: 内蒙古启讯科技信息有限公司
 * Tel: 15648133366（微信）
 */

namespace app\api\controller;

use app\common\model\Product;
use app\common\model\CourseList;
use app\common\model\WatchList;
use think\Exception;
use think\Request;
use think\Db;
use think\Session;

/**
 * Class Course
 * @package app\api\controller
 */
class ApiCourse
{
    /**
     * @get(/course/index)
     */
    public function index()
    {
        $product = new Product();
        $res = $product->getCourse(1, 6);
        return json($res);
    }

    /**
     * 创建课程播放记录
     * Route::rule('play_start', 'api/ApiCourse/start');
     */
    public function start(Request $request)
    {
        $userId = Session::get('user')['user_id'];
        if (!$userId) {
            $userId = $request->post('user_id');
            if (!$userId) {
                return json(['code' => 0, 'msg' => '您还没有登录']);
            }
        };

        // 接收章节目录编号
        $id = $request->post('id');

        // 读取某个课程下面的详细课程条目，如课程编号41为java课程，110为第一章第一课的记录主键，这里的id为110，假设
        $video = new CourseList();
        $video = $video->find($id);
        if (!$video) {
            $this->error('暂无该章节！');
        }

        // 某人学习某课程的记录
        $start = new WatchList();
        $start = $start->where('user_id', $userId)->where('course_id', $video->course_id)->find();
        if (!$start) {
            $start = new WatchList();
        }

        // 更新了学习记录表
        $start->save(['menu_id' => $id, 'course_id' => $video->course_id, 'user_id' => $userId, 'updateat' => date('Y-m-d H:i:s', time())]);
        //添加播放时长记录
        $find_time_record = Db::table('bk_video_time')->where(['user_id' => $userId, 'menu_id' => $id])->find();
        if (!$find_time_record) {
            $insertData = [
                'user_id' => $userId,
                'menu_id' => intval($id),
                'sec' => 0,
                'watch_time' => time(),
                'is_complate' => 0,
                'duration' => 0
            ];
            Db::table('bk_video_time')->insert($insertData);
        }
        return json(
            array(
                'code' => 1,
                'msg' => '记录成功'
            )
        );
    }

    /**
     * 页面离开或每隔30秒更新视频播放时间
     * Route::rule('play_unload', 'api/ApiCourse/startsss');
     */
    public function startsss(Request $request)
    {
        $id = $request->post('id');
        $time = $request->post('time');
        $userId = Session::get('user')['user_id'];
        if (!$userId) {
            //$userId = $request->post('user_id');
            if (!$userId) {
                //$this->error('用户不存在或未登录');
                return json(['code' => 0, 'msg' => '您还没有登录']);
            }
        };
        $data['menu_id'] = $id;
        $data['sec'] = $time;
        $data['user_id'] = $userId;
        $inse = db('video_time')->where('menu_id', $id)->where('user_id', $userId)->find();
        if ($time > $inse['sec'] && $inse['is_complate'] == 0) {
            db('video_time')->where('menu_id', $id)->where('user_id', $userId)->update(['sec' => $time, 'watch_time' => time()]);
        }
        //查询视频时长
        $all_time = Db::table('bk_course_video')->where('menu_id', $id)->value('time');
        if (!$all_time) {
            return json_encode(['code' => -1, 'msg' => '视频不存在']);
        }
        $time_length = explode(':', $all_time);
        if (isset($time_length[1])) {
            $length = (int)$time_length[0] * 3600 + (int)$time_length[1] * 60 + (int)$time_length[2] - 10;
            $percent = round($time / $length * 100, 0);
            return json_encode(['code' => 1, 'msg' => '更新成功', 'percent' => "已完成" . $percent . "%"]);
        }
        return json_encode(['code' => -2, 'msg' => '视频时长缺失']);
    }

    /**
     * 播放完成
     * Route::rule('play_complate', 'api/ApiCourse/startsssss');
     */
    public function startsssss(Request $request)
    {
        $id = $request->post('id');
        $userId = Session::get('user')['user_id'];
        if (!$userId) {
            $userId = $request->post('user_id');
            if (!$userId) {
                //$this->error('用户不存在或未登录');
                return json(['code' => 0, 'msg' => '您还没有登录']);
            }
        };
        $data['menu_id'] = $id;
        $data['user_id'] = $userId;
        $inse = db('video_time')->where('menu_id', $id)->where('user_id', $userId)->find();
        $timesss = db('course_video')->where('menu_id', $id)->find();
        $times = explode(':', $timesss['time']);
        $timeone = $times[0] * 3600;
        $timetwo = $times[1] * 60;
        $time = $timeone + $timetwo + $times[2];
        if ($inse) {
            $updateData = ['sec' => $time, 'watch_time' => time(), 'is_complate' => 1];
            $inse = db('video_time')->where('menu_id', $id)->where('user_id', $userId)->update($updateData);
            return json(['code' => 1, 'msg' => '观看任务完成，更新成功']);
        } else {
            $data['sec'] = $time;
            $data['watch_time'] = time();
            $data['is_complate'] = 1;
            db('video_time')->insert($data);
            return json(['code' => 1, 'msg' => '观看任务完成，插入成功']);
        }
    }
}